import xml.dom.minidom

def getProjectName(path):
    config = xml.dom.minidom.parse(path)
    projectDescription = config.getElementsByTagName('projectDescription')[0]
    name = projectDescription.getElementsByTagName('name')[0].firstChild.data
    return name

import fileinput

def getProjectTarget(path):
    inputfile = fileinput.input(path)
    for line in inputfile:
        if line.startswith('target='):
            inputfile.close()
            return line[len('target='):].strip()

import commands

def updateProject(path):
    name = getProjectName(path + '/.project')
    target = getProjectTarget(path + '/project.properties')
    cmd = 'android update project --path ' + path + ' --name ' + name + ' --target ' + target
    print commands.getoutput(cmd)

def getReferencedProjects(path):
    projects = []
    inputfile = fileinput.input(path)
    for line in inputfile:
        if line.startswith('android.library.reference.'):
            proj = line[len('android.library.reference.1='):].strip()
            projects.append(proj)
    inputfile.close()
    return projects

import platform

def main():
    if platform.system() != 'Linux' and platform.system() != 'Darwin':
        print "This script targets at Linux/MacOS platforms only."
        return;
    updateProject('.');
    for p in getReferencedProjects('project.properties'):
        updateProject(p)

if '__main__' == __name__ :
    main()
